//用于数据初始化和事件处理

//添加测试数据
var testFeature = new ol.Feature(new ol.geom.Point([117.40049, 39.13981]));
testFeature.set("type", "Point1");
testFeature.set("featureId", ["wo-01", "wo-02"]);
testFeature.set("index", [2, 2]);
//初始化画笔
Draw.init();
/**
 * 初始化弹出层操作
 */
MapUtil.createMeasureTooltip();
MapUtil.createHelpTooltip();
MapUtil.createTagTooltip();
MapUtil.createOperateTooltip();
//添加放大缩小控件
$(".ol-overlaycontainer-stopevent").first().prepend("<div id='zoomIn' class='zoomIn' ></div>");
$(".ol-overlaycontainer-stopevent").first().prepend("<div id='zoomOut' class='zoomOut' ></div>");
//添加省市街控件
$(".ol-overlaycontainer-stopevent").first().prepend($("#holder")[0]);
$(".holder div").each(function() {
	$(this).click(function() {
		map.getView().setZoom(level[$(this).attr("class")]);
	});
});
/**
 *交互控制
 */
$("#PathMenu .PathItem").slice(0, 7).each(function() {
	$(this).toggle(function(){
		type = $(this).attr("id");
		MapUtil.testType(type);
		Draw.setActive(true);
	},function(){
		sameType[$(this).attr("id")] = false;
		Draw.setActive(false);
	});
});
/*
 * 定位
 */
$("#move").click(function() {
	var line = new ol.Feature(new ol.geom.LineString([
		[117.39304, 39.13470],
		[117.39504, 39.13670]
	]));
	source.addFeature(line);
	MapUtil.location(line);
	MapUtil.lineHight(line);
});
/*
 * 地图切换
 */
$("#toggleMap").toggle(function(){
	senseLayer.setVisible(true);
	normalLayer.setVisible(false);
},function(){
	normalLayer.setVisible(true);
	senseLayer.setVisible(false);
});
/**
 * 放大缩小控制
 */
$("#zoomIn, #centerIn" ).click(function() {
	var zoom = map.getView().getZoom();
	map.getView().setZoom(zoom + 1);
});
$("#zoomOut, #centerOut").click(function() {
	var zoom = map.getView().getZoom();
	map.getView().setZoom(zoom - 1);
});
//为控件绑定事件
$(".ol-zoomslider").bind({
	mouseenter: function() {
		clearTimeout(slider);
		clearTimeout(holde);
		$(".holder").show();
	},
	mouseleave: function() {
		slider = setTimeout("$('.holder').hide()", 2000);
	}
});
$(".holder").bind({
	mouseenter: function() {
		clearTimeout(slider);
		clearTimeout(holde);
		$(".holder").show();
	},
	mouseleave: function() {
		holde = setTimeout("$('.holder').hide()", 2000);
	}
});
//查询
$("#getData").click(function() {
	/*$.ajax({
		type:"post",
		url:"js/data.json",
		dataType: "json",
		success:function(data){
			var features = (new ol.format.GeoJSON()).readFeatures(data);
			source.addFeatures(features);
			MapUtil.location(testFeature);
			MapUtil.pointHight(testFeature);
		}
	});*/
	$.getJSON("js/data.json", function(data) {
		var features = (new ol.format.GeoJSON()).readFeatures(data);
		source.addFeatures(features);
		source.addFeature(testFeature);
		MapUtil.pointHight(testFeature);
	})
});
/**
 * 针对鼠标移动事件做处理，弹出提示框
 * @param {Object} evt
 */
var pointerMoveHandler = function(evt) {
	if (evt.dragging) {
		return;
	}
	/** @type {string} */
	var helpMsg = '单击确定起点，双击结束';
	/*if (sketch) {
		var geom = (sketch.getGeometry());
		if (geom instanceof ol.geom.Polygon) {
			helpMsg = continuePolygonMsg;
		} else if (geom instanceof ol.geom.LineString) {
			helpMsg = continueLineMsg;
		}
	}*/
	helpTooltipElement.innerHTML = helpMsg;
	helpTooltip.setPosition(evt.coordinate);
	$(helpTooltipElement).removeClass('hidden');
};
//帮助信息
//map.on('pointermove', pointerMoveHandler);
map.on("click", function(evt) {
	if (sketch) {
		if (type == "Range") {
			var geom = (sketch.getGeometry());
			var tooltipCoord = evt.coordinate;
			var output;
			output = MapUtil.formatLength(geom);
			if (tooltipCoord[0] == geom.getFirstCoordinate()[0] && tooltipCoord[1] == geom.getFirstCoordinate()[1]) {
				return;
			}
			if (output == "0 m") {
				return;
			}
			MapUtil.createTempTooltip();
			tempTooltipElement.innerHTML = output;
			tempTooltip.setPosition(tooltipCoord);
			geomFeature.push(tempTooltip);
		}
	}
});
$(map.getViewport()).on('mouseout', function() {
	$(helpTooltipElement).addClass('hidden');
});

/**
 * 拖动
 */
function Drag() {
	ol.interaction.Pointer.call(this, {
		handleDownEvent: Drag.prototype.handleDownEvent,
		handleMoveEvent: Drag.prototype.handleMoveEvent
	});
	this.coordinate_ = null;
	this.cursor_ = 'pointer';
	this.feature_ = null;
	this.previousCursor_ = undefined;
}
ol.inherits(Drag, ol.interaction.Pointer);
Drag.prototype.handleDownEvent = function(evt) {
	var map = evt.map;
	var feature = map.forEachFeatureAtPixel(evt.pixel,
		function(feature, layer) {
			return feature;
		}
	);
	if (feature && !Draw.getActive()) {
		this.feature_ = feature;
		if (this.feature_.get("type") == "Range" || this.feature_.get("type") == "Measure") {
			return false;
		}
		operateTooltip.setPosition(evt.coordinate);
		return true;
	} else {
		operateTooltip.setPosition();
		return false;
	}
};
Drag.prototype.handleMoveEvent = function(evt) {
	var map = evt.map;
	var feature = map.forEachFeatureAtPixel(evt.pixel,
		function(feature, layer) {
			return feature;
	});
	var element = evt.map.getTargetElement();
	//编程思想
	if (feature && !Draw.getActive()) {
		if (element.style.cursor != this.cursor_) {
			this.previousCursor_ = element.style.cursor;
			element.style.cursor = this.cursor_;
		}
	} else if (this.previousCursor_ !== undefined) {
		element.style.cursor = this.previousCursor_;
		this.previousCursor_ = undefined;
	}
};
//删除选中的feature
Drag.prototype.removeFeature = function() {
	var flag = true
	var start = this.feature_.getGeometry().getFirstCoordinate();
	var wo_extent = MapUtil.calExtent(start,50);
	if (this.feature_.getGeometry() instanceof ol.geom.Point) {
		source.forEachFeatureIntersectingExtent(wo_extent, function(feature) {
			if (feature.getGeometry() instanceof ol.geom.LineString) {
				flag = false;
				return;
			}
		});
	}
	if(flag){
		source.removeFeature(this.feature_);
		operateTooltip.setPosition();
	}else{
		alert("Cann't delete!");
	}
};
//操作feature
Drag.prototype.operateFeature = function(evt) {
	operateTooltip.setPosition();
};
var drag = new Drag();
map.addInteraction(drag);
/**
 * 拉框查询
 */
var dragBox = new ol.interaction.DragBox({
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: "red",
			lineDash:[10,5]
		}),
	}),
	condition: ol.events.condition.mouseOnly
});
dragBox.on("boxend", function(evt) {
	$("#search").click();
	var geom = this.getGeometry();
	//获得查询区域，向后台发送数据，实现查询，并将结果显示
	console.log(geom.getExtent());
	console.log(geom.getCoordinates());
});
dragBox.setActive(false);
map.addInteraction(dragBox);
$("#search").toggle(function() {
	MapUtil.testType("search");
	$("#search .link").css("background-image", "url(img/bg-item-2x-1.png)");
	dragBox.setActive(true);
}, function() {
	sameType["search"] = false;
	$("#search .link").css("background-image", "url(img/bg-item-2x.png)");
	dragBox.setActive(false);
});
/**
 * 拉框放大缩小
 */
var zoomInOut = new ol.interaction.DragBox({
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: "gray",
			lineDash:[10,5]
		}),
	}),
	condition: ol.events.condition.mouseOnly
});
zoomInOut.on("boxstart", function(evt) {
	zoomInOut.set("start",evt.coordinate);
});
zoomInOut.on("boxend", function(evt) {
	var start = zoomInOut.get("start");
	var end = evt.coordinate;
	var geom = this.getGeometry();
	if(end[0] > start[0]){
		view.setZoom(view.getZoom() + 1);
		view.setCenter(geom.getInteriorPoint().getCoordinates());
	}else{
		view.setZoom(view.getZoom() - 1);
		view.setCenter(geom.getInteriorPoint().getCoordinates());
	}
});
zoomInOut.setActive(false);
map.addInteraction(zoomInOut);
$("#zoomInOut").toggle(function() {
	MapUtil.testType("zoomInOut");
	$("#zoomInOut .link").css("background-image", "url(img/bg-item-2x-1.png)");
	zoomInOut.setActive(true);
}, function() {
	sameType["zoomInOut"] = false;
	$("#zoomInOut .link").css("background-image", "url(img/bg-item-2x.png)");
	zoomInOut.setActive(false);
});
/**
 * 拖动
 */
var modify = new ol.interaction.Modify({
	features: source.getFeaturesCollection()
});
modify.setActive(false);
map.addInteraction(modify);
$("#dragMap").toggle(function() {
	$("#map").css("cursor", "crosshair");
	MapUtil.testType("dragMap");
	$("#dragMap .link").css("background-image", "url(img/bg-item-2x-1.png)");
	modify.setActive(true);
}, function() {
		sameType["dragMap"] = false;
		$("#dragMap .link").css("background-image", "url(img/bg-item-2x.png)");
		$("#map").css("cursor", "auto");
		modify.setActive(false);
});
/**
 * 前一屏 后一屏 事件绑定
 */
map.on("moveend",function(evt){
	if(userHandle){
		userHandle = false;
	}else{
		if(!resolutionPan){
			var resolutionCenter=[];
			resolutionCenter.push(view.getCenter());
			resolutionCenter.push(view.getZoom()); 
			beforeStep.push(resolutionCenter);
			if(beforeStep.length > 1){
				$("#beforeStep .link").css("background-image", "url(img/bg-item-2x-1.png)");
			}
		}else{
			resolutionPan = false;
		}
	}

});
view.on("change:resolution",function(evt){
	resolutionPan = true;
	if(userHandle){
		userHandle = false;
	}else{
		var resolutionCenter = [];
		resolutionCenter.push(view.getCenter());
		resolutionCenter.push(view.getZoom()); 
		beforeStep.push(resolutionCenter);
		if(beforeStep.length > 1){
			$("#beforeStep .link").css("background-image", "url(img/bg-item-2x-1.png)");
		}
	}
});

$("#beforeStep").click(function(){
	if(beforeStep.length == 1){
		return;
	}
	var resolutionCenter = beforeStep.pop();
	if(beforeStep.length == 1){
		$("#beforeStep .link").css("background-image", "url(img/bg-item-2x.png)");
	}
	afterStep.push(resolutionCenter);
	$("#afterStep .link").css("background-image", "url(img/bg-item-2x-1.png)");
	resolutionCenter = beforeStep[beforeStep.length-1];
	userHandle = true;
	view.setZoom(resolutionCenter[1]);
	view.setCenter(resolutionCenter[0]);
});
$("#afterStep").click(function(){
	if(afterStep.length == 0){
		return;
	}
	var resolutionCenter = afterStep.pop();
	if(afterStep.length == 0){
		$("#afterStep .link").css("background-image", "url(img/bg-item-2x.png)");
	}
	beforeStep.push(resolutionCenter);
	$("#beforeStep .link").css("background-image", "url(img/bg-item-2x-1.png)");
	userHandle = true;
	view.setZoom(resolutionCenter[1]);
	view.setCenter(resolutionCenter[0]);
});
